package security;

import edu.umd.cs.findbugs.annotations.NonNull;
import io.jooby.Route;
import io.jooby.StatusCode;

import java.lang.reflect.Method;

public class LoginFilter implements Route.Filter {
    public static final String LOGIN_SESSION_FIELD="username";
    public static final String REDIRECT_SESSION_FIELD="redirect";
    @NonNull
    @Override
    public Route.Handler apply(@NonNull Route.Handler next) {
        return ctx -> {
            Method mvcMethod=ctx.getRoute().getMvcMethod();
            if(mvcMethod!=null && mvcMethod.isAnnotationPresent(NeedLogin.class)){
                if (ctx.session(LOGIN_SESSION_FIELD).isMissing()){
                    String requestPath=ctx.getRequestPath();
                    ctx.session().put(REDIRECT_SESSION_FIELD,requestPath);
                    ctx.sendRedirect(StatusCode.TEMPORARY_REDIRECT,"/login");
                }else {
                    return next.apply(ctx);
                }

            }
            return next.apply(ctx);
        };
    }
}
